<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\AdviceRule;
use Illuminate\Http\Request;
use App\Http\Controllers\Health\HealthController;

class AutoAdviceController extends Controller
{
	private function getCurrentUser(){
		$uc = new UserController();
		return $uc->getCurrentUser();
	}
	
	public function management(){
		return view('autoAdvice.management',['name'=>$this->getCurrentUser()->name,'rules'=>$this->getRules()]);
	}

	public function addRule(Request $r){
		$po=new AdviceRule();
		$po->title=$r->get('title');
		$po->describe=$r->get('describe');
		$po->rule=$r->get('rule');
		$po->content=$r->get('content');
		$po->save();
		return $this->management();
	}

	public function deleteRule(Request $r){
		$id=$r->get('deleteRuleId');
		AdviceRule::destroy($id);
		return $this->management();
	}

	public function getRules(){
		return AdviceRule::query()->get();
	}

	public function getAdvicesForMe(){
		$rules=$this->getRules();
		$advices=array();
		foreach($rules as $autoAdvice){
			$rule=new Rule();
			eval($autoAdvice->rule);
			$this->fillUserData($rule);
			if(eval($rule->assert)){
				array_push($advices,$autoAdvice->content);
			}
		}
		return $advices;
	}
	
	private function fillUserData(Rule $rule){
		$this->fillUserHealthData($rule);
		$counter=0;
		foreach($rule->data as $d){
			if($d==null){
				continue;
			}
			$counter++;
			$rule->sum+=$d;
			if($rule->max==null||$d>$rule->max){
				$rule->max=$d;
			}
			if($rule->min==null||$d<$rule->min){
				$rule->min=$d;
			}
			if($d>$rule->top){
				$rule->overTime++;
			}
			if($d<$rule->bottom){
				$rule->belowTime++;
			}
		}
		if($counter!=0){
			$rule->avg=$rule->max/$counter;
		}
	}
	
	private function fillUserHealthData(Rule $rule){
		$hc=new HealthController();
		switch ($rule->dateType){
			case "血压":
				return $hc->getBloodPressureRecently($rule->activeTime);
			case "心率":
				return $hc->getHeartRateRecently($rule->activeTime);
			case "运动时间":
				return $hc->getSportTimeRecently($rule->activeTime);
			default:
				return array();
		}
	}
}

class Rule {
	//系统提供的属性
	public $data=array();//数据数组，data[0]表示今天的数据，data[x]表示x天前的数据，可能不存在，不存在值为null
	public $avg=null;//表示数据的平均值
	public $max=null;//表示数据的最大值
	public $min=null;//表示数据的最小值
	public $sum=0;//表示数据的和
	public $overTime=0;//表示超过建议最大值的天数
	public $belowTime=0;//表示低于建议最小值的天数
	//用户需要设置的属性
	public $activeTime=null;//生效的时间，后面加一个正整数x，表示对近x天内的数据进行分析
	public $dateType=null;//数据类型，后面加一个字符串，表示对用户的哪项数据进行分析，可使用“血压”、“心率”、“运动时间”
	public $top=null;//表示建议最大值
	public $bottom=null;//表示建议最小值
	public $assert=null;//断言，断言为字符串表达式，如果该表达式为真，则向用户发出建议
}